import React, { Component } from "react"
import TreeCard from "./Tree-Card";
import ReactDom from 'react-dom'
import LineArrow from "./Line-Arrow";

class ViewTree extends Component {

  state = {
    display: [],
    data: [],
    route: []
  };

  componentDidMount() {
    const { data } = this.props;
    this.getMax(data);
    this.setState({ data, route: this.getRoute(data) });
  };

  getMax = data => {
    let max = 0;
    data.map(item => {
      if (item.childNodes) {
        max = this.getMax(item.childNodes);
        item.max = max;
      } else {
        max += 1;
        item.max = 1;
      }
    });
    return max;
  };

  getRoute = (data, route = [], id = null) => {
    const { display } = this.state;
    data.map(item => {
      if (id) {
        route.push([`card-${id}`, `card-${item.id}`]);
      }
      if (item.childNodes) {
        if (display.indexOf(item.id) > -1)
          return -1;
        route = this.getRoute(item.childNodes, route, item.id);
      }
    });
    return route
  };

  componentDidUpdate = () => {
    const { route } = this.state;
    ReactDom.render(<div>
      {route.map(item => (
        <LineArrow
          from={item[0]}
          to={item[1]}
        />
      ))}
    </div>, document.querySelector('.view-tree-arrow'))
  };

  renderTree = data => {
    const { display } = this.state;
    return data.map(item => {
      return (
        <TreeCard data={item} key={item.id} onChange={this.handleDisplay} display={display.indexOf(item.id) > -1}>
          {this.renderTree(item.childNodes  || [])}
        </TreeCard>
      )
    })
  };

  handleDisplay = (id, useChildNodes) => {
    const { display, data } = this.state;
    useChildNodes ? display.delete(id) : display.push(id);
    this.setState({ display, route: this.getRoute(data) });
  };

  render() {
    const { data } = this.state;
    return (<div>
      <div className={'view-tree-arrow'} style={{
        width: '100%',
        height: '100%',
        position: 'absolute',
        left: 0,
        top: 0
      }}/>
      {this.renderTree(data)}
    </div>)
  }

}

export default ViewTree
